#include "include/TcpClient.h"
#include "include/tools.h"

#define BUFFER_SIZE 1450

TcpClient::TcpClient() {}

TcpClient::TcpClient(const char *host, int port)
{
    // 1创建套接字socket
    cli_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (cli_fd < 0) {
        perror("soket error");
        return;
    }
    int optval = 1;
    setsockopt(cli_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    set_SIGPIPEN_NULL(); // 防止中断SIGPIPE后被强制退出
    //  地址
    bzero(&serv, sizeof(serv)); // 该函数初始化serv
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);
    serv.sin_addr.s_addr = inet_addr(host);
}
TcpClient::~TcpClient()
{
    close(cli_fd);
}
int TcpClient::start()
{
    // 3开始绑定
    // 连接服务器，成功返回0，错误返回-1
    if (connect(cli_fd, (struct sockaddr *)&serv, sizeof(serv)) < 0) {
        perror("connect error2");
        return 0;
    }
    return worker();
}

int TcpClient::worker()
{
    char sendbuf[BUFFER_SIZE];
    char recvbuf[BUFFER_SIZE];

    //
    printf("连接已经建立，输入发送的内容：\n");

    while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL) {
        /*每次读取一行，读取的数据保存在buf指向的字符数组中，成功，则返回第一个参数buf；*/
        /// 发送
        send(cli_fd, sendbuf, strlen(sendbuf), 0);
        if (strcmp(sendbuf, "exit\n") == 0)
            break;
        /// 接收
        recv(cli_fd, recvbuf, sizeof(recvbuf), 0);
        fputs(recvbuf, stdout);
        fputs("\n", stdout);
        // 接受或者发送完毕后把数组中的数据全部清空（置0）
        memset(sendbuf, 0, sizeof(sendbuf));
        memset(recvbuf, 0, sizeof(recvbuf));
    }

    return 0;
}

int testTcpClient()
{
    TcpClient *cli = new TcpClient("127.0.0.1", 8000);
    cli->start();
    return 0;
}
